package services

import (
	_ "errors"
	"web2/pkg/models"
	"web2/pkg/repositories"
)

type ProductService interface {
	GetAllProducts() ([]models.Product, error)
	GetProduct(id uint) (*models.Product, error)
	CreateProduct(req models.CreateProductRequest) (*models.Product, error)
	UpdateProduct(id uint, req models.UpdateProductRequest) (*models.Product, error)
	DeleteProduct(id uint) error
}

type productService struct {
	repo repositories.ProductRepository
}

func NewProductService(repo repositories.ProductRepository) ProductService {
	return &productService{repo: repo}
}

func (s *productService) GetAllProducts() ([]models.Product, error) {
	return s.repo.FindAll()
}

func (s *productService) GetProduct(id uint) (*models.Product, error) {
	return s.repo.FindByID(id)
}

func (s *productService) CreateProduct(req models.CreateProductRequest) (*models.Product, error) {
	product := &models.Product{
		Name:          req.Name,
		Model:         req.Model,
		Brand:         req.Brand,
		CategoryID:    req.CategoryID,
		Specs:         req.Specs,
		Unit:          req.Unit,
		PurchasePrice: req.PurchasePrice,
		RetailPrice:   req.RetailPrice,
		MinStock:      req.MinStock,
		MaxStock:      req.MaxStock,
		Description:   req.Description,
	}

	if err := s.repo.Create(product); err != nil {
		return nil, err
	}

	return product, nil
}

func (s *productService) UpdateProduct(id uint, req models.UpdateProductRequest) (*models.Product, error) {
	product, err := s.repo.FindByID(id)
	if err != nil {
		return nil, err
	}

	// 只更新提供的字段
	if req.Name != nil {
		product.Name = *req.Name
	}
	if req.Model != nil {
		product.Model = *req.Model
	}
	if req.Brand != nil {
		product.Brand = *req.Brand
	}
	if req.CategoryID != nil {
		product.CategoryID = *req.CategoryID
	}
	if req.Specs != nil {
		product.Specs = *req.Specs
	}
	if req.Unit != nil {
		product.Unit = *req.Unit
	}
	if req.PurchasePrice != nil {
		product.PurchasePrice = *req.PurchasePrice
	}
	if req.RetailPrice != nil {
		product.RetailPrice = *req.RetailPrice
	}
	if req.MinStock != nil {
		product.MinStock = *req.MinStock
	}
	if req.MaxStock != nil {
		product.MaxStock = *req.MaxStock
	}
	if req.Description != nil {
		product.Description = *req.Description
	}

	if err := s.repo.Update(id, product); err != nil {
		return nil, err
	}

	return product, nil
}

func (s *productService) DeleteProduct(id uint) error {
	return s.repo.Delete(id)
}
